package com.cash.lemoloan.statisticlib.Utils;


import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Log;

import com.cash.lemoloan.statisticlib.StatisticContant;
import com.cash.lemoloan.statisticlib.model.StatisticAPP01Info;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class AppListManager {
    private static final String TAG = "AppListManager";
    private final Context mContext;
    private final PackageManager mPackageManager;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    // 官方类别常量（兼容低版本）
    private static final String CATEGORY_APP_GALLERY = "android.intent.category.APP_GALLERY";
    private static final String CATEGORY_APP_MUSIC = "android.intent.category.APP_MUSIC";
    private static final String CATEGORY_APP_VIDEO = "android.intent.category.APP_VIDEO";
    private static final String CATEGORY_APP_FILES = "android.intent.category.APP_FILES";
    private static final String CATEGORY_APP_BROWSER = "android.intent.category.APP_BROWSER";
    private static final String CATEGORY_APP_CONTACTS = "android.intent.category.APP_CONTACTS";
    private static final String CATEGORY_APP_CALENDAR = "android.intent.category.APP_CALENDAR";
    private static final String CATEGORY_APP_MESSAGING = "android.intent.category.APP_MESSAGING";

    public AppListManager(Context context) {
        this.mContext = context;
        this.mPackageManager = context.getPackageManager();
    }

    public synchronized List<StatisticAPP01Info> getAppInfo() {
        List<StatisticAPP01Info> app01InfoList = new ArrayList<>();
        List<AppInfo> allApps = getMostCompleteAppList();
        for (AppInfo app : allApps) {
            StatisticAPP01Info app01Info = new StatisticAPP01Info();
            app01Info.setstatisticAppType(app.isSystemApp ? StatisticContant.SYSTEM : StatisticContant.NON_SYSTEM);
            app01Info.setstatisticAppName(app.appName);
            app01Info.setstatisticPackageName(app.packageName);
            app01Info.setstatisticCtime(String.valueOf(System.currentTimeMillis()));

            String firstInstallTime = formatTimeToTimestamp(app.firstInstallTime);
            app01Info.setstatisticFirstInstallTime(firstInstallTime);

            String lastUpdateTime = formatTimeToTimestamp(app.lastUpdateTime);
            app01Info.setstatisticLastUpdateTime(lastUpdateTime);

            app01Info.setstatisticVersionCode(String.valueOf(app.versionCode));
            app01Info.setstatisticVersionName(app.versionName == null ? "未知" : app.versionName);

            app01InfoList.add(app01Info);
        }
        return app01InfoList;
    }

    private String formatTimeToTimestamp(String timeStr) {
        if (timeStr == null || timeStr.equals("未知") || timeStr.contains("不支持")) {
            return String.valueOf(System.currentTimeMillis());
        }
        try {
            long timestamp = dateFormat.parse(timeStr).getTime();
            return String.valueOf(timestamp);
        } catch (ParseException e) {
            if (timeStr.matches("\\d{10}")) {
                return timeStr + "000";
            } else {
                return String.valueOf(System.currentTimeMillis());
            }
        }
    }

    /**
     * 原有Intent筛选逻辑
     */
    public List<AppInfo> getMostCompleteAppList() {
        Set<String> packageSet = new HashSet<>();
        List<AppInfo> allApps = new ArrayList<>();

        addUniqueApps(allApps, getLauncherApps(), packageSet);
        addUniqueApps(allApps, getSystemCoreApps(), packageSet);
        addUniqueApps(allApps, getBrowserApps(), packageSet);
        addUniqueApps(allApps, getContactsApps(), packageSet);
        addUniqueApps(allApps, getCalendarApps(), packageSet);
        addUniqueApps(allApps, getMessagingApps(), packageSet);
        addUniqueApps(allApps, getGalleryApps(), packageSet);
        addUniqueApps(allApps, getMusicApps(), packageSet);
        addUniqueApps(allApps, getVideoApps(), packageSet);
        addUniqueApps(allApps, getFileManagerApps(), packageSet);
        addUniqueApps(allApps, getToolApps(), packageSet);
        addUniqueApps(allApps, getLauncherHomeApps(), packageSet);
        addUniqueApps(allApps, getAppsFromInstalledApplications(), packageSet);

        return allApps;
    }

    /**
     * 基础层：通过getInstalledApplications获取全量已安装应用
     */
    private List<AppInfo> getAppsFromInstalledApplications() {
        List<AppInfo> appList = new ArrayList<>();
        // 根据Android版本设置最优标志位（兼容低版本）
        int flags = PackageManager.GET_META_DATA;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            flags |= PackageManager.MATCH_ALL; // Android 11+ 全量匹配
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            flags |= PackageManager.MATCH_UNINSTALLED_PACKAGES; // Android 7+ 包含未完全卸载应用
        }

        try {
            // 调用系统API获取全量应用的ApplicationInfo
            List<ApplicationInfo> systemApps = mPackageManager.getInstalledApplications(flags);
            for (ApplicationInfo appInfo : systemApps) {
                // 过滤无效包名（避免空指针）
                if (appInfo.packageName == null || appInfo.packageName.trim().isEmpty()) {
                    continue;
                }
                // 转换为自定义AppInfo模型（带异常防护）
                AppInfo customAppInfo = convertToCustomAppInfo(appInfo);
                if (customAppInfo != null) {
                    appList.add(customAppInfo);
                }
            }
        } catch (SecurityException e) {
            Log.e(TAG, "获取全量应用：权限不足（需检查应用列表权限）", e);
        } catch (Exception e) {
            Log.e(TAG, "获取全量应用：系统API调用失败", e);
        }
        return appList;
    }

    /**
     * 工具方法：将系统ApplicationInfo转换为自定义AppInfo（带异常防护）
     */
    private AppInfo convertToCustomAppInfo(ApplicationInfo systemAppInfo) {
        AppInfo customAppInfo = new AppInfo();
        try {
            // 1. 基础包名（必传）
            customAppInfo.packageName = systemAppInfo.packageName;

            // 2. 应用名称（优先加载Label，失败用包名兜底）
            try {
                CharSequence label = systemAppInfo.loadLabel(mPackageManager);
                customAppInfo.appName = label != null ? label.toString() : systemAppInfo.packageName;
            } catch (Exception e) {
                customAppInfo.appName = systemAppInfo.packageName;
            }

            // 3. 应用图标（失败用null兜底，避免崩溃）
            try {
                customAppInfo.appIcon = systemAppInfo.loadIcon(mPackageManager);
            } catch (Exception e) {
                customAppInfo.appIcon = null;
            }

            // 4. 版本信息（通过PackageInfo获取）
            PackageInfo packageInfo = mPackageManager.getPackageInfo(systemAppInfo.packageName, 0);
            customAppInfo.versionName = packageInfo.versionName;
            // 版本号兼容：Android 9+ 用long型，低版本用int型
            customAppInfo.versionCode = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
                    ? packageInfo.getLongVersionCode()
                    : packageInfo.versionCode;

            // 5. 安装/更新时间（时间戳转字符串，无效时间用"未知"兜底）
            customAppInfo.firstInstallTime = formatDate(packageInfo.firstInstallTime);
            customAppInfo.lastUpdateTime = formatDate(packageInfo.lastUpdateTime);

            // 6. 系统/用户应用区分（通过ApplicationInfo标志位判断）
            customAppInfo.isSystemApp = (systemAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
            customAppInfo.isUserApp = !customAppInfo.isSystemApp;

        } catch (PackageManager.NameNotFoundException e) {
            return null;
        } catch (Exception e) {
            return null;
        }
        return customAppInfo;
    }

    private List<AppInfo> getLauncherApps() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        int flags = PackageManager.MATCH_DISABLED_COMPONENTS;

        // 处理不同Android版本的标志位兼容性
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            flags |= PackageManager.MATCH_UNINSTALLED_PACKAGES;
        }
        if (Build.VERSION.SDK_INT >= 33) {
            flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
        }

        return getAppInfoList(intent, flags);
    }

    private List<AppInfo> getSystemCoreApps() {
        List<AppInfo> systemApps = new ArrayList<>();

        Intent preferenceIntent = new Intent(Intent.ACTION_MAIN);
        preferenceIntent.addCategory(Intent.CATEGORY_PREFERENCE);
        systemApps.addAll(getAppInfoList(preferenceIntent, 0));

        Intent infoIntent = new Intent(Intent.ACTION_MAIN);
        infoIntent.addCategory(Intent.CATEGORY_INFO);
        systemApps.addAll(getAppInfoList(infoIntent, 0));

        return systemApps;
    }

    private List<AppInfo> getBrowserApps() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_BROWSER);
        }
        return getAppInfoList(intent,
                PackageManager.MATCH_DEFAULT_ONLY |
                        PackageManager.MATCH_DISABLED_COMPONENTS);
    }

    private List<AppInfo> getContactsApps() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType("vnd.android.cursor.dir/contact");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_CONTACTS);
        }
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getCalendarApps() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType("vnd.android.cursor.dir/event");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_CALENDAR);
        }
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getMessagingApps() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_MESSAGING);
        }
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getGalleryApps() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_GALLERY);
        }
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getMusicApps() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType("audio/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_MUSIC);
        }
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getVideoApps() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType("video/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_VIDEO);
        }
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getFileManagerApps() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.addCategory(CATEGORY_APP_FILES);
        }
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getToolApps() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        return getAppInfoList(intent, 0);
    }

    private List<AppInfo> getLauncherHomeApps() {
        List<AppInfo> homeApps = new ArrayList<>();

        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory(Intent.CATEGORY_HOME);
        homeApps.addAll(getAppInfoList(homeIntent, 0));

        return homeApps;
    }

    private void addUniqueApps(List<AppInfo> allApps, List<AppInfo> newApps, Set<String> packageSet) {
        for (AppInfo app : newApps) {
            if (app.packageName != null && !packageSet.contains(app.packageName)) {
                packageSet.add(app.packageName);
                allApps.add(app);
            }
        }
    }

    private List<AppInfo> getAppInfoList(Intent intent, int flags) {
        List<AppInfo> appInfoList = new ArrayList<>();

        try {
            List<ResolveInfo> resolveInfos = mPackageManager.queryIntentActivities(intent, flags);

            for (ResolveInfo resolveInfo : resolveInfos) {
                String packageName = resolveInfo.activityInfo.packageName;
                AppInfo appInfo = new AppInfo();

                appInfo.packageName = packageName;
                appInfo.appName = resolveInfo.loadLabel(mPackageManager).toString();
                appInfo.appIcon = resolveInfo.loadIcon(mPackageManager);

                try {
                    PackageInfo packageInfo;
                    if (Build.VERSION.SDK_INT >= 33) {
                        packageInfo = mPackageManager.getPackageInfo(packageName, 0);
                    } else {
                        packageInfo = mPackageManager.getPackageInfo(packageName, 0);
                    }

                    appInfo.versionName = packageInfo.versionName;
                    appInfo.versionCode = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
                            ? packageInfo.getLongVersionCode()
                            : packageInfo.versionCode;

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        appInfo.firstInstallTime = formatDate(packageInfo.firstInstallTime);
                        appInfo.lastUpdateTime = formatDate(packageInfo.lastUpdateTime);
                    } else {
                        appInfo.firstInstallTime = "不支持（Android 8.0+可用）";
                        appInfo.lastUpdateTime = "不支持（Android 8.0+可用）";
                    }

                    ApplicationInfo applicationInfo = packageInfo.applicationInfo;
                    appInfo.isSystemApp = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
                    appInfo.isUserApp = (applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
                            && !appInfo.isSystemApp;

                } catch (PackageManager.NameNotFoundException e) {
                    Log.e(TAG, "获取包信息失败: " + packageName, e);
                    appInfo.versionName = "未知";
                    appInfo.versionCode = -1;
                    appInfo.firstInstallTime = "未知";
                    appInfo.lastUpdateTime = "未知";
                    appInfo.isSystemApp = false;
                    appInfo.isUserApp = false;
                }

                appInfoList.add(appInfo);
            }
        } catch (Exception e) {
            Log.e(TAG, "获取应用列表失败", e);
        }

        return appInfoList;
    }

    private String formatDate(long timestamp) {
        if (timestamp <= 0) {
            return "未知";
        }
        return dateFormat.format(new Date(timestamp));
    }

    /**
     * 完整的应用信息实体类
     */
    public static class AppInfo {
        public String packageName;       // 包名
        public String appName;           // 应用名称
        public Drawable appIcon;         // 图标
        public boolean isSystemApp;      // 是否系统应用
        public boolean isUserApp;        // 是否用户应用
        public String versionName;       // 版本名称
        public long versionCode;         // 版本号
        public String firstInstallTime;  // 第一次安装时间
        public String lastUpdateTime;    // 最近更新时间

        @Override
        public String toString() {
            return "AppInfo{" +
                    "packageName='" + packageName + '\'' +
                    ", appName='" + appName + '\'' +
                    ", versionName='" + versionName + '\'' +
                    ", versionCode=" + versionCode +
                    ", firstInstallTime='" + firstInstallTime + '\'' +
                    ", lastUpdateTime='" + lastUpdateTime + '\'' +
                    '}';
        }
    }
}
